'''A multiprocess implementation of the papyros API.'''

__all__ = ['MultiProcessTaskDispatcher', 'MultiProcessWorker']

import time
import weakref
from processing import Process

from papyros import log, detect_cpus
from papyros.base import TaskDispatcher, Worker, ClosedTaskDispatcherError


class MultiProcessTaskDispatcher(TaskDispatcher):

    def __init__(self, size=0, num_workers=0, timeout=1.0):
        TaskDispatcher.__init__(self, size)
        if not num_workers:
            num_workers = detect_cpus()
        self.__workers = [MultiProcessWorker(self, timeout, 'Worker-%d' % i)
                         for i in xrange(num_workers)]
        for worker in self.__workers:
            worker.start()
        log.debug('%s started %d worker threads', self, num_workers)


class MultiProcessWorker(Process, Worker):

    def __init__(self, dispatcher, timeout, name=None):
        Process.__init__(self, name=name)
        Worker.__init__(self, weakref.proxy(dispatcher))
        self.__timeout = timeout
        #self.setDaemon(True)

    def run(self):
        timeout = self.__timeout
        while self.is_connected():
            try:
                if not self.execute_task():
                    time.sleep(timeout)
            except (ClosedTaskDispatcherError, weakref.ReferenceError), ex:
                print type(ex)
                self.disconnect()
            #except KeyboardInterrupt:
            #    #self.disconnect()
            #    self.terminate()
